import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

# 冒泡排序可视化函数
def bubble_sort_visualization(ax):
    ax.clear()
    data = np.random.randint(0, 100, 15)  # 生成随机数据
    bars = ax.bar(range(len(data)), data, color='blue')  # 绘制柱形图

    # 记录每一步比较的索引
    comparisons = []

    # 冒泡排序算法，同时记录比较过程
    def bubble_sort(data):
        comparisons = []
        n = len(data)
        for i in range(n):
            for j in range(0, n - i - 1):
                comparisons.append((j, j + 1))
                if data[j] > data[j + 1]:
                    data[j], data[j + 1] = data[j + 1], data[j]
        return comparisons

    # 获取所有的比较步骤
    comparisons = bubble_sort(data.copy())

    # 更新动画每一帧的函数
    def update(frame):
        if frame < len(comparisons):
            i, j = comparisons[frame]
            ax.clear()
            bars = ax.bar(range(len(data)), data, color='blue')
            if data[i] > data[j]:
                data[i], data[j] = data[j], data[i]  # 交换数据
            bars[i].set_color('red')  # 高亮显示正在比较的柱形
            bars[j].set_color('red')  # 高亮显示正在比较的柱形
        else:
            ax.clear()
            bars = ax.bar(range(len(data)), data, color='blue')
        ax.set_title("Bubble Sort Visualization")
        return bars

    # 创建动画
    ani = animation.FuncAnimation(ax.figure, update, frames=range(len(comparisons) + 10), interval=100, repeat=False)
    return ani
